<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\cms\controller;


use function PHPSTORM_META\type;
use think\admin\Controller;
use think\facade\Config;
use think\admin\service\AdminService;
use think\admin\extend\DataExtend;
use think\admin\service\MenuService;




/**
 * 设备生产厂家台账
 * Class Qiyedevice
 * @package app\wechat\controller
 */
class Qiyemanufacturer extends BaseController
{

    /**
     * 当前操作数据库
     * @var string
     */
    protected $table = 'CmsQiye';
    protected $qiye_type = 'manufacturer';

    /**
     * 生产厂家台账管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = "燃气设备生产厂家";
        $map = ["type"=>$this->qiye_type,'is_deleted' => '0'];
        $this->type = $this->qiye_type;
        //根据like后的字段来进行搜索
        $query = $this->_query($this->table)->like('name')->where($map)->order('sort desc,id desc');
        $query->whereNotIn('id', ['subscribe', 'default'])->order('sort desc,id desc')->page();
    }

    public function widget()
    {
        $map = ["type"=>$this->qiye_type];
        $query = $this->_query($this->table)->like('name')->where($map)->order('sort desc,id desc');
        $query->whereNotIn('id', ['subscribe', 'default'])->order('sort desc,id desc')->page();
    }

    public function ajaxSearch()
    {
        $limit = 5;
        $page = intval($this->request->request('page',1));
        $offset = ($page-1)*$limit;
        $map = ["type"=>$this->qiye_type];
        $name = $this->request->request('name');
        if($name!=""){
            $category = $this->app->db->name('CmsQiye')
                ->where($map)
                ->whereLike("name","%$name%")
                ->order("id desc")
                ->limit($offset,$limit)->select()->toArray();
            $total = $this->app->db->name('CmsQiye')
                ->where($map)
                ->whereLike("name","%$name%")->count();
        }else{
            $category = $this->app->db->name('CmsQiye')
                ->where($map)
                ->order("id desc")
                ->limit($offset,$limit)->select()->toArray();
            $total = $this->app->db->name('CmsQiye')->where($map)->count();
        }
        $this->success("成功",array("list"=>$category,"total"=>$total,"limit"=>$limit));
    }

    /**
     * [0:"aaa",1:"bbb"]
     * @return array  {"ccc":"aaa","222":"2222'}
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _get_category_dict(){
        $result = array();
        $category = $this->app->db->name('CmsCategory')->select()->toArray();
        foreach ($category as $value){
            $result[$value['id']] = $value['title'];
        }
        return $result;
    }

    /**
     * 数据列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _index_page_filter(&$data)
    {

    }

    /**
     * 表单数据处理
     * @param array $vo
     * @throws \ReflectionException
     */
    protected function _form_filter(&$vo)
    {

        if ($this->request->isGet()) {
            // 清理权限节点
            AdminService::instance()->clearCache();


            // 读取系统功能节点
            $this->nodes = MenuService::instance()->getList();

        }

    }

    /**
     * 添加设备生产厂家
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function add()
    {

        if ($this->request->isGet()) {
            $this->_applyFormToken();
            $this->_form($this->table, 'form');
        } else {

            $update = $this->request->post('data', []);
            $update['type'] = $this->qiye_type;
            $update[ 'create_by']   = AdminService::instance()->getUserId();
            $update[ 'update_at'] = $update[ 'create_at'] = time();
            if ($this->app->db->name($this->table)->insert($update) !== false) {
                $this->success('添加成功！','javascript:history.back()');
            } else {
                $this->error('添加失败，请稍候再试！');
            }
        }
    }


    /**
     * 编辑设备生产厂家
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->type= $this->request->get('type');
        $this->category_id= $this->request->get('category_id');
        //$map = ["type" =>$this->type];
        $map = array();
        $this->clist = $this->app->db->name('CmsCategory')->where($map)->select()->toArray();
        foreach ( $this->clist as &$vo) {
            $vo['ids'] = join(',', DataExtend::getArrSubIds( $this->clist, $vo['id'], $key = 'id', $pkey = 'parent_id'));
        }
        $this->clist = DataExtend::arr2table( $this->clist, $key="id", $pkey="parent_id");
        for ($i=0;$i<count($this->clist);$i++) {
            //var_dump($this->type);
            if($this->clist[$i]['type']!=$this->type){
               // var_dump($this->clist[$i]);
                $this->clist[$i]['disable'] = true;
               // $arr[$this->clist[$i]['disable']] = true;
            }else{
               // $arr[$this->clist[$i]['disable']] = false;
                $this->clist[$i]['disable'] = false;
            }
        }
             //var_dump($this->clist);
        $this->id = $this->request->get('id');
        $map = array("id" => $this->id);
        if (empty($this->id)) $this->error('参数错误，请稍候再试！');
        if ($this->request->isGet()) {
            if ($this->request->get('output') === 'json') {
                $this->success('获取数据成功！', $this->app->db->name($this->table)->where($map)->find());
            } else {
                $this->title = '编辑企业信息';
                $this->_applyFormToken();
                $this->_form($this->table, 'form');
            }
        }else{
            $data = $this->request->post('data', []);
            $data['update_at'] = time();
            if ($this->app->db->name($this->table)->where($map)->update($data) !== false) {
                $this->success('企业信息更新成功！', 'javascript:history.back()');
            } else {
                $this->error('企业信息更新失败，请稍候再试！');
            }
        }

    }

    /**
     * 删除设备生产厂家
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

    /**
     * 导出
     */
    public function export(){

        $name = $this->request->get("name");
        $title = [array("name","名称"), array("addr","联系地址"),
            array("contacts","联系人"), array("phone","联系电话")];
        $data = $this->prepareExportData($name);
        $this->exportExcel($title, $data);
    }

    private function prepareExportData($name){
        $query = $this->app->db->name($this->table)->field("name,addr,contacts,phone");
        if($name)
            $query = $query->whereLike("name","%".$name."%");
        return $query->order("id desc")->select();
    }

    public function import(){
        //$inputFileName = "F:\\phpStudy\\GasPortalProject\\temp\\01simple.xlsx";
        //$inputFileName = "http://127.0.0.1:9500/upload/63/1fcfb478ee9a562f929784a1b44e64.xlsx";
        $inputFileName = $this->request->request("url");
        $inputFileName = $this->filerFilePath($inputFileName);

        $fields = [ "name", "addr", "contacts", "phone" ];
        $res = $this->importExcel($inputFileName, $fields, 2, array("type"=>$this->qiye_type));
        if($res['status']==0){
            $this->error($res['info']);
        }
        $this->success($res['info']);

    }
}
